<template>
  <view class="detail-view">
    <view class="top-view clearfix"></view>
    <view class="form-cont">
      <!-- 客户信息卡片 -->
      <view class="card-block customer-card">
        <view
          class="card-title"
          @click="goPage('/pagesT/customer/selCustomer')"
        >
          <view class="card-title-left ellipsis">{{
            add_form.customerName
          }}</view>
          <u-icon color="#FB5904" name="arrow-right" size="28"></u-icon>
        </view>
        <view class="address-view">
          <view class="remark_cont" v-if="add_form.customerName === '选择客户'"
            >+{{
              add_form.deliveryType !== 2 ? "选择收货信息" : "选择自提点"
            }}</view
          >
          <block v-else>
            <view
              @click="openSelect('address_show')"
              class="remark_particulars"
              v-if="add_form.deliveryType !== 2"
            >
              <block v-if="address_list.length > 0">
                <view class="clearfix">
                  <view class="float_left"
                    >联系人：{{
                      address_list[address_index].name || "--"
                    }}</view
                  >
                  <view class="float_right" style="color: #fb5904">{{
                    address_list[address_index].mobile || "--"
                  }}</view>
                </view>
                <view class="site">
                  {{ address_list[address_index].area.provinceName
                  }}{{ address_list[address_index].area.cityName
                  }}{{ address_list[address_index].area.districtName
                  }}{{ address_list[address_index].area.address }}
                </view>
              </block>
              <block v-else>
                <view style="text-align: left">
                  <text style="margin-right: 30rpx">暂无收货信息</text>
                  <u-icon name="plus" size="24" color="#FB5904"></u-icon>
                  <text
                    style="color: #fb5904"
                    @click="
                      goPage(
                        `/pagesT/order/AddShippingAddress?customerId=${add_form.customerId}`
                      )
                    "
                    >去新增</text
                  >
                </view>
              </block>
              <view class="arrow-right-icon"
                ><u-icon color="#FB5904" name="arrow-right" size="24"></u-icon
              ></view>
            </view>
            <view
              @click="openSelect('express_show')"
              class="remark_particulars"
              v-else
            >
              <block v-if="self_express_list.length > 0">
                <view class="clearfix">
                  <view class="float_left"
                    >自提点：{{
                      self_express_list[express_rule_index].name || "--"
                    }}</view
                  >
                  <view class="float_right" style="color: #fb5904">{{
                    self_express_list[express_rule_index].mobile || "--"
                  }}</view>
                </view>
                <view class="site">{{
                  self_express_list[express_rule_index].addressName
                }}</view>
              </block>
              <block v-else>
                <view style="text-align: left">
                  <text style="margin-right: 30rpx">暂无自提点</text>
                  <u-icon name="plus" size="24" color="#FB5904"></u-icon>
                  <text
                    style="color: #fb5904"
                    @click="
                      goPage(
                        `/pagesT/order/AddShippingAddress?customerId=${add_form.customerId}`
                      )
                    "
                    >去新增</text
                  >
                </view>
              </block>
              <view class="arrow-right-icon"
                ><u-icon color="#FB5904" name="arrow-right" size="24"></u-icon
              ></view>
            </view>
          </block>
        </view>
      </view>

      <!-- 商品清单卡片 -->
      <view class="card-block goods-card">
        <view class="goods-title-row">
          <view class="goods-title-left">商品清单</view>
          <view class="goods-title-right">
            <text>共{{ goods_list.length }}种，{{ numTotal }}件</text>
            <u-icon
              name="scan"
              size="44"
              color="#333"
              class="choose-goods"
              @click="barCode"
            ></u-icon>
            <u-icon
              name="plus"
              size="44"
              color="#FB5904"
              class="choose-goods"
              @click="selGoods"
            ></u-icon>
            <u-icon
              v-if="goods_list.length"
              name="trash"
              size="44"
              color="#999"
              class="choose-goods"
              @click="clearGoods"
            ></u-icon>
          </view>
        </view>
        <!-- 商品列表直接平铺展示 -->
        <view class="goods-list-container" v-if="goods_list.length">
          <view
            class="goods-item"
            v-for="(item, index) in goods_list"
            :key="index"
          >
            <view class="goods-item-header">
              <view class="goods-name">{{ item.title }}</view>
              <view class="goods-delete" @click="delGoods(index)">
                <u-icon name="close" size="24" color="#999"></u-icon>
              </view>
            </view>
            <view class="goods-item-content">
              <image
                class="goods-image"
                :src="item.images[0]"
                mode="aspectFill"
              ></image>
              <view class="goods-info">
                <view class="goods-code">{{ item.code }}</view>
                <view class="goods-spec">
                  {{ item.unitName }};
                  <text v-for="(sku, skuI) in item.specGroup" :key="skuI"
                    >{{ sku.specValueName }};</text
                  >
                </view>
              </view>
              <view class="goods-price-qty">
                <view class="goods-price">
                  <text>单价：</text>
                  <input
                    :disabled="!$accessCheck($Access.OrderAddeditGoodsPrice)"
                    class="price-input"
                    type="digit"
                    v-model="item.salePrice"
                  />
                  <text>元</text>
                </view>
                <view class="goods-qty" v-if="item.isEq === 4">
                  <u-number-box
                    :min="0"
                    :index="index"
                    @change="addBuyNumChange"
                    :value="item.buyNum"
                  ></u-number-box>
                </view>
                <view class="goods-qty" v-else>
                  <view class="qty-row">
                    <text>数量：</text>
                    <input
                      class="qty-input"
                      type="digit"
                      v-model="item.buyNum"
                    />
                  </view>
                  <view class="qty-row">
                    <text>其他单位：</text>
                    <input
                      class="qty-input"
                      type="digit"
                      v-model="item.otherNum"
                    />
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="empty-goods" v-else>
          <u-empty text="未选择商品" mode="data"></u-empty>
        </view>
      </view>

      <!-- 订单信息卡片 -->
      <view class="card-block form-card">
        <view class="form-item-row">
          <view class="form-label">配送方式</view>
          <view class="form-value clickable" @click="openDelivery">
            {{ deliveryType_name || "请选择配送方式" }}
            <u-icon name="arrow-right" size="24" color="#FB5904"></u-icon>
          </view>
        </view>
        <view class="form-item-row" v-if="add_form.deliveryType === 3">
          <view class="form-label">物流类型</view>
          <view
            class="form-value clickable"
            @click="particularsType_show = true"
          >
            {{ particularsType_name || "请选择物流类型" }}
            <u-icon name="arrow-right" size="24" color="#FB5904"></u-icon>
          </view>
        </view>
        <view class="form-item-row">
          <view class="form-label">支付方式</view>
          <view class="form-value clickable" @click="payType_show = true">
            {{ payType_name || "请选择支付方式" }}
            <u-icon name="arrow-right" size="24" color="#FB5904"></u-icon>
          </view>
        </view>
      </view>

      <!-- 金额信息卡片 -->
      <view class="card-block money-card">
        <view class="money-row">
          <view class="money-label">商品总额</view>
          <view class="money-value highlight">{{
            $utils.formattedNumber(totalMoney)
          }}</view>
        </view>
        <view class="money-row">
          <view class="money-label">订单优惠</view>
          <view class="money-value error-value">
            <input
              placeholder="请输入订单优惠"
              placeholder-class="input-pl"
              :disabled="!$accessCheck($Access.OrderAddeditGoodsPrice)"
              class="dis-input input-sj"
              type="digit"
              @focus="totalReduceMoneyFocus"
              @blur="totalReduceMoneyBlur"
              v-model="add_form.totalReduceMoney"
            />
          </view>
        </view>
        <view class="money-row">
          <view class="money-label">应收</view>
          <view class="money-value highlight">{{
            $utils.formattedNumber(payMoney)
          }}</view>
        </view>
        <view class="money-row">
          <view class="money-label">实收</view>
          <view class="money-value error-value">
            <input
              class="dis-input input-sj"
              placeholder="请输入实收金额"
              placeholder-class="input-pl"
              :disabled="!$accessCheck($Access.OrderAddeditGoodsPrice)"
              type="digit"
              @focus="receivedMoneyFocus"
              @blur="receivedMoneyBlur"
              v-model="add_form.receivedMoney"
            />
          </view>
        </view>
        <view class="money-row">
          <view class="money-label">结算账户</view>
          <view
            class="money-value clickable"
            @click="
              goPage('/pagesT/account/selAccount?shopId=' + account_shopId)
            "
          >
            {{ accountName || "请选择结算账户" }}
            <u-icon name="arrow-right" size="24" color="#FB5904"></u-icon>
          </view>
        </view>
      </view>

      <!-- 备注卡片 -->
      <view class="card-block remark-card">
        <view class="bz-label">订单备注</view>
        <view class="bz-value"
          ><u-input type="textarea" v-model="add_form.remark"
        /></view>
      </view>
    </view>
    <!-- 其余弹窗和底部按钮保持不变 -->
    <u-select
      @confirm="particularsTypeChange"
      v-model="particularsType_show"
      label-name="label"
      value-name="value"
      :list="particularsType_list"
    ></u-select>
    <u-select
      @confirm="deliveryTypeChange"
      v-model="delivery_show"
      label-name="title"
      value-name="deliveryType"
      :list="deliveryType_list"
    ></u-select>
    <u-select
      @confirm="payTypeChange"
      v-model="payType_show"
      label-name="label"
      value-name="value"
      :list="payType_list"
    ></u-select>
    <u-select
      v-model="address_show"
      value-name="id"
      label-name="name"
      :list="address_list"
      @confirm="addressChange"
    ></u-select>
    <u-select
      v-model="express_show"
      value-name="id"
      label-name="name"
      :list="self_express_list"
      @confirm="expressChange"
    ></u-select>
    <view class="detail-bottom"
      ><u-button
        class="handel-btnu"
        @click="submit"
        :loading="sub_load"
        :ripple="true"
        type="primary"
        >提交订单</u-button
      ></view
    >

    <!-- 扫码弹窗 -->
    <u-popup
      v-model="scan_popup_show"
      mode="center"
      width="90%"
      height="85%"
      border-radius="20"
      :z-index="99999"
      @close="closeScanPopup"
    >
      <view class="scan-popup">
        <u-navbar :is-back="false" :is-fixed="false">
          <view class="navbar-content">
            <view class="navbar-title">扫码</view>
          </view>
        </u-navbar>
        <view class="scan-popup-content">
          <camera
            v-if="show_camera"
            mode="scanCode"
            device-position="back"
            flash="off"
            @error="cameraError"
            class="scan-camera"
            @scancode="onScanCode"
          ></camera>
          <view v-else class="camera-placeholder" @click="show_camera = true">
            <u-icon name="camera-fill" size="80" color="#ccc"></u-icon>
            <text>点击开启摄像头</text>
          </view>
          <view class="scan-tip">将条码放入框内，即可自动扫描</view>
        </view>
        <view class="temp-list-container">
          <view class="temp-list-title">
            <text>本次已扫 {{ temp_scan_list.length }} 件</text>
            <text class="clear-temp" @click="temp_scan_list = []">清空</text>
          </view>
          <scroll-view scroll-y class="temp-list">
            <view
              class="temp-item"
              v-for="(item, index) in temp_scan_list"
              :key="index"
            >
              <text class="temp-item-name ellipsis">{{ item.title }}</text>
              <text class="temp-item-barcode">{{ item.barCode }}</text>
            </view>
            <u-empty
              text="暂无商品"
              mode="list"
              v-if="!temp_scan_list.length"
            ></u-empty>
          </scroll-view>
        </view>
        <view class="scan-popup-footer">
          <u-button type="primary" @click="closeScanPopup">完成</u-button>
        </view>
      </view>
    </u-popup>

    <Tabbar v-model="tabbar_current"></Tabbar>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tabbar_current: 2,
      sub_load: false,
      express_show: false,
      address_show: false,
      goodsData: "",
      customerData: "",
      AccountData: "",
      goods_list: [],
      address_list: [],
      address_index: 0,
      deliveryType_list: [], //配送方式
      payType_list: [
        {
          label: "货到付款",
          value: 3,
        },
        {
          label: "先款后货",
          value: 9,
        },
      ],
      particularsType_list: [
        {
          label: "物流专线",
          value: 4,
        },
        {
          label: "物流专车",
          value: 5,
        },
      ],
      self_express_list: [],
      deliveryType_name: "",
      particularsType_name: "", //物流详情名称
      particularsType: "", //物流详情id
      payType_name: "货到付款", //支付方式名称
      delivery_show: false,
      payType_show: false,
      account_shopId: "",
      payWay: 3, //支付方式
      express_rule_index: 0,
      accountName: "",
      shop_id: "",
      order_detail: {},
      add_form: {
        deliveryType: "",
        customerName: "选择客户",
        addressId: "",
        remark: "",
        accountList: "",
        currentAccountName: "",
        receivedMoney: 0,
        lists: [],
        totalMoney: 0,
        payMoney: 0,
        totalReduceMoney: 0,
        userCenterId: "",
        customerId: "",
        selfRuleId: "",
        selfRuleData: "",
        operatorName: "",
        payType: 3, //支付方式id
      },
      rules: {
        customerName: [
          {
            required: true,
            message: "请选择客户",
            // 可以单个或者同时写两个触发验证方式
            trigger: "change",
          },
        ],
      },
      particularsType_show: false,
      // 扫码弹窗相关
      scan_popup_show: false,
      show_camera: false,
      temp_scan_list: [], // 临时扫码列表
    };
  },
  watch: {
    customerData(val) {
      if (val) {
        this.add_form.userCenterId = val.userCenterId;
        this.add_form.customerId = val.id;
        this.add_form.customerName = val.name;
        this.account_shopId = val.shopId;
        // 获取客户收货地址列表
        if (this.add_form.deliveryType !== 2) {
          this.getAllShippingAddress();
        }
      }
    },
    goodsData(val) {
      if (val) {
        uni.removeStorageSync("orderGoods");
        this.goods_list = val;
      }
    },
    AccountData(val) {
      if (val) {
        this.accountName = val.name;
        this.add_form.accountList = [
          {
            accountId: val.id,
            accountNumber: val.accountNumber,
            accountName: val.name,
            money: this.add_form.receivedMoney,
            discountMoney: 0,
            finalMoney: this.add_form.receivedMoney,
            payWay: this.payWay,
            remark: val.remark,
          },
        ];
      }
    },
  },
  computed: {
    userName() {
      return this.$store.state.userInfo.name;
    },
    numTotal() {
      if (!this.goods_list.length) {
        return 0;
      } else if (this.goods_list.length === 1) {
        return Number(this.goods_list[0].buyNum);
      } else {
        let sum = 0;
        this.goods_list.forEach((item) => {
          sum = sum + Number(item.buyNum);
        });
        return sum;
      }
    },
    // 商品总额
    totalMoney() {
      if (!this.goods_list.length) {
        return 0;
      } else if (this.goods_list.length === 1) {
        return (
          Number(this.goods_list[0].buyNum) *
          Number(this.goods_list[0].salePrice)
        );
      } else {
        let sum = 0;
        this.goods_list.forEach((item) => {
          sum = sum + Number(item.buyNum) * Number(item.salePrice);
        });
        return sum;
      }
    },
    payMoney() {
      return this.totalMoney - this.add_form.totalReduceMoney;
    },
  },
  onShow() {
    this.getAllShippingAddress();
  },
  onLoad(options) {
    if (options.customer) {
      const customer = JSON.parse(options.customer);
      this.add_form.userCenterId = customer.userCenterId;
      this.add_form.customerId = customer.customerId;
      this.add_form.customerName = customer.customerName;
      this.account_shopId = customer.shopId;
      // 获取客户收货地址列表
      this.getAllShippingAddress();
    }
    if (options.id) {
      this.order_id = options.id;
      this.add_form.userCenterId = options.userCenterId;
      uni.setNavigationBarTitle({
        title: "编辑订单",
      });
      this.getOrderInfoById();
    } else {
      this.add_form.currentAccountName = this.userName;
    }
    this.getAllDelivery();
    // 获取自提点
    this.getAllSelfExpressRule();
  },
  methods: {
    // 详情
    getOrderInfoById() {
      this.$u.api
        .getOrderInfoById(this.add_form.userCenterId, {
          orderId: this.order_id,
        })
        .then(({ data }) => {
          uni.stopPullDownRefresh();
          this.order_detail = data;
          this.deliveryType_name = data.deliveryName;
          if (data.accountList && data.accountList.length) {
            this.accountName = data.accountList[0].accountName;
          }

          //由于订单是按照店铺拆单的
          // 所以在编辑订单时，增加此订单的商品时应该只能选择本店铺下的商品
          this.shop_id = data.shopId;
          this.account_shopId = data.shopId;
          this.add_form = {
            deliveryType: data.deliveryType,
            customerName: data.customerName,
            addressId: "",
            remark: data.remark,
            accountList: data.accountList,
            currentAccountName: data.currentAccountName,
            receivedMoney: data.receivedMoney,
            totalMoney: data.totalMoney,
            payMoney: data.payMoney,
            totalReduceMoney: data.totalReduceMoney,
            userCenterId: data.userCenterId,
            customerId: data.customerId,
            selfRuleId: data.selfRuleId,
            selfRuleData: data.selfRuleData,
            operatorName: data.operatorName,
            payType: Number(data.payType),
          };
          if (this.add_form.payType === 9) {
            this.payType_name = "先款后货";
          }
          if (this.add_form.deliveryType === 4) {
            this.add_form.deliveryType = 3;
            this.deliveryType_name = "物流";
            this.particularsType = 4;
            this.particularsType_name = "物流专线";
          }
          if (this.add_form.deliveryType === 5) {
            this.add_form.deliveryType = 3;
            this.deliveryType_name = "物流";
            this.particularsType = 5;
            this.particularsType_name = "物流专车";
          }
          this.goods_list = data.goodsData.map((item) => {
            return {
              ...item,
              salePrice: item.price,
              title: item.goodsName,
              code: item.goodsCode,
            };
          });
          if (data.customerId) {
            // 获取客户收货地址列表
            this.getAllShippingAddress(
              this.add_form.deliveryType !== 2 ? data.receiveData.id : ""
            );
          }
          // if (this.add_form.deliveryType === 2) {
          // 	const selfRuleData = JSON.parse(data.selfRuleData);
          // } else {
          // 	const receiveData = data.receiveData;
          // }
        })
        .catch((err) => {
          uni.stopPullDownRefresh();
        });
    },
    openSelect(key) {
      this[key] = true;
    },
    selGoods() {
      if (!this.add_form.customerId) {
        this.$u.toast("请选择客户");
        return;
      }
      uni.setStorageSync("orderGoods", JSON.stringify(this.goods_list));
      this.goPage("/pagesT/goods/selGoods?userCenterId=" + this.shop_id);
    },
    // 配送方式
    getAllDelivery() {
      this.$u.api
        .getAllDelivery({
          page: 1,
          pageSize: 100,
        })
        .then((res) => {
          this.deliveryType_list = res.data;
          const defaultType = res.data.find((item) => item.defaultStatus === 5);
          if (defaultType && !this.add_form.deliveryType) {
            this.add_form.deliveryType = defaultType.deliveryType;
            this.deliveryType_name = defaultType.title;
          }
        });
    },
    openDelivery() {
      this.delivery_show = true;
    },
    getAllShippingAddress(id) {
      this.$u.api
        .getAllShippingAddress(this.add_form.customerId)
        .then((res) => {
          if (res.data.length) {
            this.add_form.addressId = res.data[0].id;
            this.address_list = res.data.map((item) => {
              return {
                ...item,
                name: item.name || item.mobile,
              };
            });
          } else {
            this.address_list = [];
          }
        });
    },
    // 获取自提点
    getAllSelfExpressRule() {
      this.$u.api.getAllSelfExpressRule().then((res) => {
        this.self_express_list = res.data.map((item) => {
          return {
            ...item,
            name: item.setData.name,
            mobile: item.setData.mobile,
            addressName:
              item.setData.provinceName +
              "-" +
              item.setData.cityName +
              "-" +
              item.setData.districtName +
              "-" +
              item.setData.address,
          };
        });

        if (res.data.length) {
          this.add_form.selfRuleId = res.data[0].id;
          this.add_form.selfRuleData = res.data[0].setData;
        }
      });
    },
    // 配送方式
    deliveryTypeChange(arr) {
      this.add_form.deliveryType = arr[0].value;
      this.deliveryType_name = arr[0].label;
      if (arr[0].value === 1) {
        this.getAllShippingAddress(this.add_form.customerId);
      } else if (arr[0].value === 2) {
        if (this.self_express_list.length) {
          const target = this.self_express_list[0];
          this.add_form.selfRuleId = target.id;
          this.add_form.selfRuleData = target.setData;
        }
      }
    },
    payTypeChange(e) {
      this.payType_name = e[0].label;
      this.add_form.payType = e[0].value;
    },
    particularsTypeChange(e) {
      this.particularsType_name = e[0].label;
      this.particularsType = e[0].value;
    },
    addressChange(arr) {
      this.add_form.addressId = arr[0].value;
      this.address_index = this.address_list.findIndex(
        (item) => item.id === arr[0].value
      );
    },
    expressChange(arr) {
      this.add_form.selfRuleId = arr[0].value;
      this.add_form.selfRuleData = arr[0].setData;
      this.express_rule_index = this.self_express_list.findIndex(
        (item) => item.id === arr[0].value
      );
    },
    submit() {
      if (!this.goods_list.length) {
        this.$u.toast("请选择商品");
        return;
      }
      if (
        this.add_form.receivedMoney > 0 &&
        !this.add_form.accountList.length
      ) {
        this.$u.toast("请选择结算账户");
        return;
      }
      let lists = this.goods_list.map((item) => {
        return {
          skuId: item.skuId,
          code: item.code,
          goodsId: item.id,
          buyNum: item.buyNum,
          otherNum: item.otherNum,
          shopId: item.shopId,
          basicGoodsId: item.basicGoodsId || item.goodsBasicId,
          goodsName: item.title,
          unitName: item.unitName,
          specGroup: item.specGroup,
          inventory: item.inventory,
          salePrice: item.salePrice,
          subMoney: item.salePrice * item.buyNum,
          shopName: item.shopName,
          goodsImages: item.images[0],
          brandId: item.brandId,
          brandName: item.brandName,
          categoryPath: item.categoryPath,
          categoryName: item.categoryName,
          conversion: item.conversion,
          barCode: item.barCode,
          storageCode: item.storage,
          warehouseId: item.warehouseId,
          originPrice: item.originPrice,
          specType: item.specType,
          supplierId: item.supplierId,
          supplierName: item.supplierName,
          isEq: item.isEq,
        };
      });

      let params = {
        ...this.add_form,
        totalMoney: this.totalMoney,
        payMoney: this.payMoney,
        operatorName: this.userName,
      };
      if (this.particularsType) {
        params.deliveryType = this.particularsType;
      }
      // this.$refs.uForm.validate(valid => {
      // if (valid) {
      if (this.order_id) {
        params.goodsData = lists.map((item) => {
          return {
            ...item,
            goodsCode: item.code,
            images: [item.goodsImages],
            price: item.salePrice,
            totalMoney: item.subMoney,
          };
        });
        this.sub_load = true;
        this.$u.api
          .newOrderEdit(this.order_id, {
            ...this.order_detail,
            ...params,
          })
          .then((res) => {
            this.sub_load = false;
            this.$u.toast("修改成功");
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          })
          .catch((res) => {
            this.sub_load = false;
          });
      } else {
        params.lists = lists;
        this.sub_load = true;
        this.$u.api
          .newAddOrder(params)
          .then((res) => {
            this.sub_load = false;
            this.$u.toast("下单成功");
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          })
          .catch((res) => {
            this.sub_load = false;
          });
      }
      // }
      // });
    },
    delGoods(index) {
      this.goods_list.splice(index, 1);
    },
    addBuyNumChange({ value, index }) {
      const target = this.$u.deepClone(this.goods_list);
      if (Number(value) === 0) {
        target.splice(index, 1);
      } else {
        target[index].buyNum = value;
      }
      this.goods_list = target;
    },
    clearGoods() {
      uni.showModal({
        title: "提示",
        content: "确定要清空所有商品吗？",
        success: (res) => {
          if (res.confirm) {
            this.goods_list = [];
          }
        },
      });
    },
    // 打开扫码弹窗
    openScanPopup() {
      if (!this.add_form.customerId) {
        this.$u.toast("请选择客户");
        return;
      }
      this.temp_scan_list = [];
      this.scan_popup_show = true;
      // 延迟开启摄像头，避免卡顿
      setTimeout(() => {
        this.show_camera = true;
      }, 200);
    },
    // 关闭扫码弹窗
    closeScanPopup() {
      this.show_camera = false;
      this.scan_popup_show = false;
      this.mergeScanList();
    },
    // 摄像头扫码成功
    onScanCode(e) {
      console.log("scancode:", e.detail.result);
      if (!e.detail.result) return;
      // 震动提示
      uni.vibrateShort();
      this.handleBarCode(e.detail.result);
    },
    cameraError(e) {
      console.log("camera error:", e.detail);
      this.$u.toast("摄像头初始化失败，请检查权限");
      this.show_camera = false;
    },
    handleBarCode(result) {
      this.$u.api
        .getGoodsByBarCode({
          barCode: result,
        })
        .then((res) => {
          if (!res.data || !res.data.detail) {
            this.$u.toast("未找到该商品");
            return;
          }
          const detail = res.data.detail;

          // 检查主列表和临时列表中是否已存在 (by skuId)
          const in_main_list = this.goods_list.some(
            (item) => item.skuId === detail.skuId
          );
          const in_temp_list = this.temp_scan_list.some(
            (item) => item.skuId === detail.skuId
          );

          if (in_main_list || in_temp_list) {
            this.$u.toast("该商品已存在");
            return;
          }

          this.temp_scan_list.unshift({
            ...detail,
            buyNum: 1,
          });
          this.$u.toast("添加成功");
        })
        .catch((err) => {
          this.$u.toast("商品信息获取失败");
          console.error("扫码获取商品失败", err);
        });
    },
    // 合并扫码列表到主列表
    mergeScanList() {
      if (!this.temp_scan_list.length) return;

      // 去重，防止意外的重复添加
      const new_items = this.temp_scan_list.filter((temp_item) => {
        return !this.goods_list.some(
          (main_item) => main_item.skuId === temp_item.skuId
        );
      });

      this.goods_list.push(...new_items);
      this.temp_scan_list = []; // 清空临时列表
    },
    barCode() {
      // 旧的扫码逻辑，现在改为弹窗
      this.openScanPopup();
    },
    sendBarCode(result) {
      // 旧的扫码逻辑，保留以防万一，但主要逻辑已移至 handleBarCode
      this.$u.api
        .getGoodsByBarCode({
          barCode: result,
        })
        .then((res) => {
          const detail = res.data.detail;
          const index = this.goods_list.findIndex(
            (item) => item.skuId === detail.skuId
          );
          if (index !== -1) {
            this.$u.toast("该商品已在列表中");
          } else {
            this.goods_list.push({
              ...detail,
              buyNum: 1,
            });
            this.$u.toast("添加成功");
          }
        });
    },
    // 实收输入框获取焦点
    receivedMoneyFocus() {
      if (!this.add_form.receivedMoney || this.add_form.receivedMoney <= 0) {
        this.add_form.receivedMoney = "";
      }
    },
    // 实收输入框失去焦点
    receivedMoneyBlur() {
      if (!this.add_form.receivedMoney || this.add_form.receivedMoney <= 0) {
        this.add_form.receivedMoney = 0;
      }
    },
    // 订单优惠输入框获取焦点
    totalReduceMoneyFocus(key) {
      if (
        !this.add_form.totalReduceMoney ||
        this.add_form.totalReduceMoney <= 0
      ) {
        this.add_form.totalReduceMoney = "";
      }
    },
    // 订单优惠输入框失去焦点
    totalReduceMoneyBlur() {
      if (
        !this.add_form.totalReduceMoney ||
        this.add_form.totalReduceMoney <= 0
      ) {
        this.add_form.totalReduceMoney = 0;
      }
    },
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    // this.$refs.uForm.setRules(this.rules);
  },
};
</script>

<style lang="scss" scoped>
.top-view {
  background: linear-gradient(180deg, #fb5904, #fb7a37, #ff8f59, #f5f5f6 100%);
  height: 360rpx;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  z-index: -1;
}

.form-cont {
  // transform: translateY(70rpx);
  position: relative;
  z-index: 1;
  padding-bottom: 80rpx;
}

.card-block {
  width: 710rpx;
  background-color: #fff;
  margin: 24rpx auto 0 auto;
  border-radius: 0;
  padding: 0 32rpx 0 32rpx;
  box-shadow: none;
  border: 1px solid #f0f0f0;
}

.customer-card {
  padding-top: 0;
  padding-bottom: 16rpx;

  .card-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx 0 24rpx 0;

    .card-title-left {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
}

.goods-card {
  padding-top: 0;
  padding-bottom: 16rpx;

  .goods-title-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx 0 24rpx 0;

    .goods-title-left {
      font-size: 28rpx;
      font-weight: 600;
      color: #333;
    }

    .goods-title-right {
      display: flex;
      align-items: center;

      text {
        font-size: 24rpx;
        color: #999;
        margin-right: 12rpx;
      }

      .choose-goods {
        margin-left: 20rpx;
        vertical-align: middle;
        cursor: pointer;
      }
    }
  }

  .goods-list-container {
    padding-bottom: 16rpx;

    .goods-item {
      background-color: #ffffff;
      border-radius: 8rpx;
      margin-bottom: 16rpx;
      border: 1px solid #f0f0f0;

      &:last-child {
        margin-bottom: 0;
      }

      .goods-item-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16rpx 20rpx;
        border-bottom: 1px solid #f0f0f0;

        .goods-name {
          font-size: 28rpx;
          font-weight: 500;
          color: #333;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .goods-delete {
          padding: 8rpx;
        }
      }

      .goods-item-content {
        display: flex;
        padding: 20rpx;
        flex-wrap: wrap;

        .goods-image {
          width: 120rpx;
          height: 120rpx;
          border-radius: 8rpx;
          margin-right: 20rpx;
          border: 1px solid #f0f0f0;
        }

        .goods-info {
          flex: 1;
          margin-right: 20rpx;

          .goods-code {
            font-size: 24rpx;
            color: #666;
            margin-bottom: 8rpx;
          }

          .goods-spec {
            font-size: 24rpx;
            color: #999;
          }
        }

        .goods-price-qty {
          width: 100%;
          display: flex;
          justify-content: space-between;
          margin-top: 20rpx;
          padding-top: 16rpx;
          border-top: 1px dashed #f0f0f0;

          .goods-price {
            display: flex;
            align-items: center;
            font-size: 26rpx;
            color: #fb5904;

            .price-input {
              width: 120rpx;
              text-align: center;
              font-size: 26rpx;
              color: #fb5904;
              margin: 0 8rpx;
              background-color: #f8f8f8;
              border-radius: 4rpx;
              padding: 4rpx 8rpx;
            }
          }

          .goods-qty {
            .qty-row {
              display: flex;
              align-items: center;
              font-size: 26rpx;
              color: #666;
              margin-bottom: 10rpx;

              &:last-child {
                margin-bottom: 0;
              }

              .qty-input {
                width: 100rpx;
                text-align: center;
                font-size: 26rpx;
                color: #666;
                margin-left: 8rpx;
                background-color: #f8f8f8;
                border-radius: 4rpx;
                padding: 4rpx 8rpx;
              }
            }
          }
        }
      }
    }
  }

  .empty-goods {
    padding: 40rpx 0;
  }
}

.form-card {
  padding-top: 0;
  padding-bottom: 0;

  .form-item-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .form-label {
      font-size: 26rpx;
      color: #999;
    }

    .form-value {
      font-size: 26rpx;
      color: #2d405e;

      &.clickable {
        color: #fb5904;
        display: flex;
        align-items: center;
        cursor: pointer;
      }
    }
  }
}

.money-card {
  padding-top: 0;
  padding-bottom: 0;

  .money-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .money-label {
      font-size: 28rpx;
      color: #333;
      font-weight: 600;
    }

    .money-value {
      font-size: 28rpx;
      color: #2d405e;
      font-weight: 600;

      &.highlight {
        color: #fb5904;
        font-size: 32rpx;
      }

      &.error-value {
        color: #f67778;
      }

      &.clickable {
        color: #fb5904;
        cursor: pointer;
        display: flex;
        align-items: center;
      }
    }
  }
}

.remark-card {
  padding-top: 0;
  padding-bottom: 0;

  .bz-label {
    line-height: 80rpx;
    font-weight: bold;
    color: #333;
  }

  .bz-value {
    padding-bottom: 24rpx;
  }
}

.address-view {
  border-top: 1px solid #f0f0f0;
  line-height: 48rpx;
  height: 142rpx;
  font-size: 28rpx;

  .remark_cont {
    width: 200rpx;
    margin: 0 auto;
    line-height: 142rpx;
    color: #fb5904;
    font-size: 28rpx;
  }

  .remark_particulars {
    padding: 24rpx 0;
    padding-right: 24rpx;
    color: #666;
    font-size: 26rpx;
    position: relative;

    .arrow-right-icon {
      position: absolute;
      right: -10rpx;
      top: 50%;
      transform: translateY(-50%);
    }
  }
}

.detail-bottom {
  margin: 40rpx auto;
  width: 100%;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 99;

  .handel-btnu {
    width: 90%;
    height: 80rpx;
    border-radius: 40rpx;
    background: linear-gradient(90deg, #fb5904, #ff8f59);
    border-color: #fb5904;
    color: #ffffff;
    box-shadow: 0 4rpx 8rpx rgba(251, 89, 4, 0.3);
  }
}

.scan-popup {
  width: 100%;
  height: 100%;
  background-color: #f4f4f5;
  display: flex;
  flex-direction: column;
  border-radius: 20rpx;
  overflow: hidden;
  .navbar-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding: 0 30rpx;
    color: #fff;
    .navbar-title {
      font-size: 32rpx;
    }
  }
  .scan-popup-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
    .scan-camera {
      width: 100%;
      height: 100%;
    }
    .camera-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #ccc;
      font-size: 28rpx;
    }
    .scan-tip {
      position: absolute;
      bottom: 40rpx;
      color: #fff;
      background-color: rgba(0, 0, 0, 0.5);
      padding: 10rpx 20rpx;
      border-radius: 20rpx;
    }
  }
  .temp-list-container {
    background-color: #fff;
    height: 40%; // 调整列表高度
    display: flex;
    flex-direction: column;
    .temp-list-title {
      padding: 20rpx 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 28rpx;
      color: #333;
      border-bottom: 1rpx solid #f0f0f0;
      .clear-temp {
        color: #fb5904;
        font-size: 26rpx;
      }
    }
    .temp-list {
      flex: 1;
      min-height: 0;
      padding: 0 30rpx;
      .temp-item {
        padding: 20rpx 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1rpx solid #f5f5f5;
        &:last-child {
          border-bottom: none;
        }
        .temp-item-name {
          font-size: 26rpx;
          color: #333;
          flex: 1;
          margin-right: 20rpx;
        }
        .temp-item-barcode {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
  .scan-popup-footer {
    background-color: #fff;
    padding: 20rpx;
    padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  }
}
</style>
